package com.tcs.test.zk.watcher;

import java.io.IOException;
import java.net.InetAddress;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.zookeeper.CreateMode;
import org.apache.curator.framework.recipes.cache.PathChildrenCache.StartMode;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tcs.test.zk.base.BaseZookeeper;

public class TreeNodeRegsterWatcher extends BaseZookeeper {
	
	private static final Logger logger = LoggerFactory.getLogger(TreeNodeRegsterWatcher.class);
	
	public static final String ZK_PATH = "/montioring";
	
	@Test
	public void treeWatcher() {
		try {
			if (null == cf.checkExists().forPath(ZK_PATH)) {
				cf.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(ZK_PATH);
			}
		} catch (Exception e) {
			logger.error("" , e);
		}
		// 4 建立一个PathChildrenCache缓存,第三个参数为是否接受节点数据内容 如果为false则不接受
		PathChildrenCache cache = new PathChildrenCache(cf, ZK_PATH, true);
		// 5 在初始化的时候就进行缓存监听
		try {
			cache.start(StartMode.POST_INITIALIZED_EVENT);
		} catch (Exception e) {
			logger.error("" , e);
		}
		try {
			InetAddress addr = InetAddress.getLocalHost();
			String ip = addr.getHostAddress().toString();
			cf.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(ZK_PATH + "/" + ip);
		} catch (Exception e) {
			logger.error("" , e);
		}
		cache.getListenable().addListener(new PathChildrenCacheListener() {
			
			@Override
			public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
				switch (event.getType()) {
				case CHILD_ADDED:
					logger.info("---CHILD_ADDED : {} , stat : {} ", event.getData().getPath() , event.getData().getStat());
					break;
				case CHILD_UPDATED:
					logger.info("---CHILD_UPDATED : {} , stat : {} ", event.getData().getPath() , event.getData().getStat());
					break;
				case CHILD_REMOVED:
					logger.info("---CHILD_REMOVED : {} , stat : {} ", event.getData().getPath() , event.getData().getStat());
					break;
				default:
					break;
				}
			}
		});
		this.block();
	}
	
	public void block() {
		try {
			System.in.read();
		} catch (IOException e) {
			logger.error("" , e);
		}
	}

}
